<template>
  <div class="contract-editor-container">
    <!-- 工具栏 -->
    <el-card class="mb-4">
      <div class="flex justify-between items-center">
        <el-text v-if="!show"> 清 账 承 诺 书</el-text>
        <h1 v-else> {{labor.title}}</h1>
        <div class="flex gap-2">
          <el-button type="primary" @click="saveContract">
            保存合同
          </el-button>
          <el-button @click="previewContract">
            预览
          </el-button>
        </div>
        <div>
        </div>
      </div>
    </el-card>
    
    <!-- 合同编辑区域 -->
    <el-card v-if="show">
      <div class="contract-content">
        <!-- 合同标题 -->
        <div class="text-center mb-8">
          <h1 class="text-2xl font-bold">服务合同</h1>
          <p class="text-left">合同编号: {{ contract.contractNumber }}</p>
        </div>
        
        <!-- 合同双方信息 -->
        <div class="mb-6">
          <div class="grid grid-cols-2 gap-6">
              <p class="font-medium">致： 苏州华雨建设科技有限公司</p>
          </div>
        </div>

        <div class="mb-6">
          <h2 class="text-xl font-semibold mb-4 border-b pb-2">一、工程概况和内容</h2>
          <p>　　我司
            <span class="edit" :contenteditable="isEdit('partyB')"  @input="onChange('partyB', $event.target)">{{ contract.partyB }}</span>
              确认：根据我司与贵司于
              <span class="edit" :contenteditable="isEdit('date')"  @input="onChange('date', $event.target)">{{ contract.date }}</span>
              签订的《劳务承包协议》，在
              <span class="edit" :contenteditable="isEdit('project')"  @input="onChange('project', $event.target)">{{ contract.project }}</span>
              项目承包的
              <span class="edit" :contenteditable="isEdit('scop')"  @input="onChange('scop', $event.target)">{{ contract.scop }}</span>
              辅料及人工费，我与贵司于约定的合同暂估金额为
              <span class="edit" :contenteditable="isEdit('valuation')"  @input="onChange('valuation', $event.target)">{{ contract.valuation }}</span>
              元，经核算最终按照人民币
              <span class="edit" :contenteditable="isEdit('price')"  @input="onChange('price', $event.target)">{{ contract.price }}</span>
              （约定金额）予以结算，我承诺贵司支付完上述款项后，前述合同项下贵司的付款义务已全部履行完毕，我无任何理由再向贵司主张其他任何款项，否则贵司有权追究我的刑事责任。</p>
        </div>

        <div class="mb-6">
          <p>　　同时我承诺上述项目全部班组人员工资均已结清，不存在拖欠工资情况，否则造成贵司一切损失及责任均由我承担。本承诺人确认，        本承诺人使用的印章为本承诺人的唯一印章，承诺人在任何文件上加盖的印章本承诺人均承认其效力和真实性(或签字)。</p>
        </div>

        <div class="mb-6">
          <p>　　特此承诺！</p>
        </div>

        <el-row>
            <el-col :span="18"></el-col>
            <el-col :span="6">
              <p>承 诺 人：<span class="edit" :contenteditable="isEdit('promisor')"  @input="onChange('promisor', $event.target)">{{ contract.promisor }}</span></p>
              <p>经办人(签字及按手印)：</p>
              <p>联系电话：：</p>
              <p>日期：</p>
            </el-col>
          </el-row>
        <!-- ------------------------------------------------------------ -->
      </div>
    </el-card>
    
    <!-- 预览弹窗 -->
    <el-dialog v-model="previewVisible" title="合同预览" width="80%">
      <div class="contract-preview" >
        <!-- 预览内容与编辑区域相同，但所有内容都不可编辑 -->
        <div ref="pdfContent" v-html="previewHtml" class="contract-content" />
      </div>
      
      <template #footer>
        <el-button type="primary" @click="exportToPdf">导出为PDF</el-button>
        <el-button @click="previewVisible = false">关闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue';
import { ElMessage, ElCard, ElButton, ElDialog } from 'element-plus';
import html2pdf from 'html2pdf.js';
import http from '../../../util/request';
const pdfContent = ref(null);

const show = ref(false)
const labor = ref({id:0,title:'',is:false});
let is = sessionStorage.getItem('labor_contract');
if(is){
  show.value = true
  labor.value = JSON.parse(is)
}
// 初始化合同数据
const contract = ref<any>({
  project: 'DK20100414地块（苏州新闻大厦）25层小演播室装饰工程（苏州日报社智能融媒体中心）',
  partyB: '苏州华靖建筑科技有限公司',
  valuation: '47000.00',
  scop:'电工',
  price:'47000.00',
  promisor: '苏州华靖建筑科技有限公司',
  date: '2028 年 12 月 31 日',
});

// 可编辑区域设置
const dialogVisible = ref(false);
const editableSections = ref<string[]>([
  'project',
  'partyB',
  'valuation',
  'scop',
  'price',
  'promisor',
  'date',
]);


// 状态管理
const isSaved = ref(false);
const previewVisible = ref(false);
const previewHtml = ref('');

// 判断区域是否可编辑
const isEdit = (section: string) => {
  return editableSections.value.includes(section);
};

// 处理内容变化
const onChange = (section:any, value: any) => {
  contract.value[section] = value.innerText;
  isSaved.value = false;
};

const getData = () => {
    http.post('/labor/template',{labor_contract_id:labor.value.id,type:'team'}).then((response:any)=>{
      if(response.data.data){
        contract.value = response.data.data.content
        labor.value.is = true
      }
      dialogVisible.value = true;
    })
}

// 保存合同
const saveContract = () => {
  // 模拟保存操作
  let request:any = null
  let content:string = JSON.stringify(contract.value)
    if(labor.value.is){
        request = http.patch('/labor/template',{labor_contract_id:labor.value.id,type:'team',content:content})
    }else{
        request = http.put('/labor/template',{labor_contract_id:labor.value.id,type:'team',content:content})
    }
    request.then((response:any)=>{
      if(response.data.code == 200){
        isSaved.value = true;
        ElMessage.success('合同已保存');
        labor.value.is = true
      }
    })
};

// 预览合同
const previewContract = () => {
  // 生成预览HTML，将所有可编辑区域变为不可编辑
  const tempDiv = document.createElement('div');
  const contractContent = document.querySelector('.contract-content')?.cloneNode(true);
  
  if (contractContent) {
    tempDiv.appendChild(contractContent);
    const editableElements = tempDiv.querySelectorAll('.edit');
    editableElements.forEach(el => {
      (el as HTMLElement).contentEditable = 'false';
      el.removeAttribute('class');
    });
    previewHtml.value = tempDiv.innerHTML;
    previewVisible.value = true;
  }
};

// 页面加载时显示可编辑区域设置按钮
onMounted(() => {
  getData();
});

// 导出PDF的方法
const exportToPdf = () => {
  if (!pdfContent.value) return;

  // 配置选项
  const opt = {
    margin: 10,
    filename: '导出的文档.pdf',
    image: { type: 'jpeg', quality: 0.98 },
    html2canvas: { scale: 2, useCORS: true },
    jsPDF: { unit: 'mm', format: 'a4', orientation: 'portrait' }
  };

  // 生成PDF
  html2pdf().from(pdfContent.value).set(opt).save();
};
</script>

<style scoped>
.contract-editor-container {
  padding: 20px;
  height: calc(100vh - 25vh);overflow-y: scroll;
}

.contract-content {
  line-height: 1.8;
  font-size: 16px;
}

.edit {
  border-bottom: 1px dashed #edd32c;
  padding: 0 4px;
  min-width: 60px;
  display: inline-block;
}

.edit[contenteditable="true"] {
  background-color: #edd32c;
  cursor: text;
}

.edit[contenteditable="true"]:focus {
  outline: 1px solid #edd32c;
  border-radius: 2px;
}

.contract-preview {
  max-height: 70vh;
  overflow-y: auto;
  padding: 20px;
}
</style>
